import { NavBar, DatePicker } from 'antd-mobile'
import './index.scss'
import { useEffect, useMemo, useState } from 'react'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
import _ from 'lodash'
import classNames from 'classnames'

const Year = () => {
    // 时间选择器的显示
    const [visible, setVisible] = useState(false)
    const [time, setTime] = useState(dayjs().format('YYYY'))

    // 获取所有账单，把账单按年分组
    const billList = useSelector(state => state.bill.billList)
    const yearGroup = useMemo(() => {
        return _.groupBy(billList, (item) => dayjs(item.date).format('YYYY'))
    }, [billList])
    // console.log(yearGroup);

    // 每一年的数据
    const [yearList, setYearList] = useState()
    const listResult = useMemo(() => {
        const pay = yearList ? yearList.filter(item => item.type === 'pay').reduce((a, c) => a + c.money, 0) : 0
        const income = yearList ? yearList.filter(item => item.type === 'income').reduce((a, c) => a + c.money, 0) : 0
        const total = income + pay
        return {
            pay,
            income,
            total
        }
    }, [yearList])
    // 初始化时，渲染当前年份的数据
    useEffect(() => {
        const nowTime = dayjs().format('YYYY')
        if (yearGroup[nowTime]) {
            setYearList(yearGroup[nowTime])
        }
    }, [yearGroup])
    
    // 选择年份
    const timeConfirm = (value) => {
        setVisible(false)
        const format = dayjs(value).format('YYYY')
        setTime(format)
        setYearList(yearGroup[format])
    }

  return (
    <div className="monthlyBill">
      <NavBar className="nav" backArrow={false}>
        年度收支
      </NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setVisible(true)}>
            <span className="text">
              {time}年账单
            </span>
            <span className={ classNames ('arrow', visible && 'expand') }></span>
          </div>
          {/* 统计区域 */}
          <div className='twoLineOverview'>
            <div className="item">
              <span className="money">{listResult.pay.toFixed(2)}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{listResult.income.toFixed(2)}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{listResult.total.toFixed(2)}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="year"
            visible={visible}
            max={new Date()}
            onConfirm={timeConfirm}
            onClose={() => setVisible(false)}
          />
        </div>
      </div>
    </div >
  )
}

export default Year